package com.citic.topview.app.security;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.UserFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.citic.topview.common.json.JsonMapper;
import com.citic.topview.common.vo.AppResultVO;

public class AppUserFilter extends UserFilter{

	private Logger logger = LoggerFactory.getLogger(AppUserFilter.class);
	
	/**
	 * 设置手机端的用户权限为appUser
	 */
    public String getLoginUrl() {
        return "/app/login/li";
    }
    
    @Override
    protected String getName() {
    	return "appUser";
    }
    
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
    	logger.info("AppUserFilter --> isAccessAllowed");
        if (isLoginRequest(request, response)) {
            return true;
        } else {
            Subject subject = getSubject(request, response);
            // If principal is not null, then the user is known and should be allowed access.
            return subject.getPrincipal() != null;
        }
    }
    
    /**
     * 当方法{@link #isAccessAllowed(javax.servlet.ServletRequest, javax.servlet.ServletResponse, Object) isAccessAllowed}
     * 拒绝请求时，进一步对rquest进行处理.
     *
     * @param request  进来的 <code>ServletRequest</code>
     * @param response 出去的 <code>ServletResponse</code>
     * @return <code>true</code> 允许继续访问; false 禁止访问并直接返回出错提示.
     * @throws Exception 处理请求出现问题.
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
    	logger.info("AppUserFilter --> onAccessDenied");
    	AppResultVO<Object> mobileResultVO = new AppResultVO<Object>();
    	mobileResultVO.setResult(AppResultVO.ERROR);
		mobileResultVO.setMessage("not login");
		mobileResultVO.setRedirect("login");
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
    	httpServletResponse.setStatus(401);  
    	JsonMapper.renderJson(mobileResultVO, response);
    	
    	return false;
    }
}
